/* 
依据开发规则,可以看出uniapp 的结构就是 index/menu ->list ->detail 的三级结构
,所以可以将其中共有的东西提取出来
 */

import h5Copy from '@/common/h5-copy.js'

var util = {
	getMonth:function(month){
		let cn_ts = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];
		let en_ts = ['January','February','March','April','May','June','July','August','September','October','November','December'];
		
		if(uni.getStorageSync('lang') == 'cn'){
			return cn_ts[month];
		}else{
			return en_ts[month];
		}
	},
	getShortMonth:function(month){
		let cn_ts = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
		let en_ts = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
		
		if(uni.getStorageSync('lang') == 'cn'){
			return cn_ts[month];
		}else{
			return en_ts[month];
		}
	},
	getWeek:function(week){
		let cn_ts = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];
		let en_ts = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
		
		if(uni.getStorageSync('lang') == 'cn'){
			return cn_ts[week];
		}else{
			return en_ts[week];
		}
	},
	getShortWeek:function(week){
		let cn_ts = ['周日','周一','周二','周三','周四','周五','周六'];
		let en_ts = ['Sun','Mon','Tues','Wed','Thur','Fri','Sat'];
		
		if(uni.getStorageSync('lang') == 'cn'){
			return cn_ts[week];
		}else{
			return en_ts[week];
		}
	},
	
	tabbar:function(url){
		uni.switchTab({
			url:url
		})
	},
	switch_tab:function(url){
		uni.switchTab({
			url:url
		});
	},
	share_weixin:function(title,href,imageUrl){
		//增加推广者的ID
		if(uni.getStorageSync('user')){
			if(href.indexOf('?') != -1){
				href = href + "&babyId=" + uni.getStorageSync('user').id;
			}else{
				href = href + "?babyId=" + uni.getStorageSync('user').id;
			}
		}
		//微信APP分享 对图片的大小进行了限制 最大允许32KB，超过的话就只显示链接了。所以需要对图片进行压缩一下。
		uni.share({
			provider: "weixin",
			scene: "WXSceneSession",
			type: 0,
			href: href,
			title: title,
			summary: "我正在使用尚云商，发现一个好的东西！",
			imageUrl: imageUrl
		});
	},
	share_weixin_quan:function(title,href,imageUrl){
		//增加推广者的ID
		if(uni.getStorageSync('user')){
			if(href.indexOf('?') != -1){
				href = href + "&babyId=" + uni.getStorageSync('user').id;
			}else{
				href = href + "?babyId=" + uni.getStorageSync('user').id;
			}
		}
		uni.share({
			provider: "weixin",
			scene: "WXSenceTimeline",
			type: 0,
			href: href,
			title: title,
			summary: "我正在使用尚云商，发现一个好的东西！",
			imageUrl: imageUrl
		});
	},
	share_copy_link:function(href){
		//增加推广者的ID
		if(uni.getStorageSync('user')){
			if(href.indexOf('?') != -1){
				href = href + "&babyId=" + uni.getStorageSync('user').id;
			}else{
				href = href + "?babyId=" + uni.getStorageSync('user').id;
			}
		}
		this.to_copy(href);
	},
	//复制到剪切板的功能 import h5Copy from '@/common/h5-copy.js'
	to_copy:function(cnt){
		// #ifdef H5
			let rs = h5Copy(cnt)
			if(rs){
				this.toast('复制成功');
			}else{
				this.toast('复制失败');
			}
		// #endif
		// #ifndef H5
			uni.setClipboardData({
				data:cnt,
				success: (res) => {
					this.toast('复制成功');
				}
			})
		// #endif
	},
	//倒计时功能
	get_count_down:function(timestamp){
		var nowTime = new Date();
		var endTime = new Date(timestamp);

		var t = endTime.getTime() - nowTime.getTime();
		var countDownTime = "00:00:00.0";
		if(t > 0) {
			var day = Math.floor(t / (24 * 3600 * 1000));
			var dayTime = t % (24 * 3600 * 1000);

			var hour = Math.floor(t / (3600 * 1000));
			var hourTime = dayTime % (3600 * 1000);

			var min = Math.floor(hourTime / (60 * 1000));
			var minTime = hourTime % (60 * 1000);

			var sec = Math.floor(minTime / 1000);
			var secTime = minTime % 1000;

			var msec = Math.floor(secTime / 100);

			if (hour < 10) {
				hour = "0" + hour;
			}
			if (min < 10) {
				min = "0" + min;
			}
			if (sec < 10) {
				sec = "0" + sec;
			}
			countDownTime = hour + ":" + min + ":" + sec + ":" + msec;
			
			return countDownTime;
		}else{
			return '活动已结束';
		}
	},
	//计算截止时间
	get_time_diff:function(endTime) {
		var diff = '';
		var time_diff = endTime - new Date().getTime();
		if(time_diff < 0){
			return '已过期';
		}
		// 计算相差天数 
		var days = Math.floor(time_diff / (24 * 3600 * 1000));
		if (days > 0) {
			diff += days + '天';
		}
		// 计算相差小时数 
		var leave1 = time_diff % (24 * 3600 * 1000);
		var hours = Math.floor(leave1 / (3600 * 1000));
		if (hours > 0) {
			diff += hours + '小时';
		} else {
			if (diff !== '') {
				diff += hours + '小时';
			}
		}
		// 计算相差分钟数 
		var leave2 = leave1 % (3600 * 1000);
		var minutes = Math.floor(leave2 / (60 * 1000));
		if (minutes > 0) {
			diff += minutes + '分';
		} else {
			if (diff !== '') {
				diff += minutes + '分';
			}
		}
		// 计算相差秒数 
		var leave3 = leave2 % (60 * 1000);
		var seconds = Math.round(leave3 / 1000);
		if (seconds > 0) {
			diff += seconds + '秒';
		} else {
			if (diff !== '') {
				diff += seconds + '秒';
			}
		}
		return diff;
	},
	//同步请求 request
	async req_sy({
		method = "GET",
		url,
		data,
	}) {
		let res = await this.req_sync({
			method,
			url,
			data
		});

		return res;
	},
	req_sync: function({
		method = "GET",
		url,
		data
	}) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: url,
				method: method,
				header: this.header(),
				complete: (res) => {
					if (res.statusCode === 200) { //成功
						resolve(res.data)
					} else {
						reject({
							flag: 1,
							msg: '网络请求失败'
						})
					}
				}
			})
		});
	},

	//对对象key进行排序 filter_data
	sortByKey: function(obj) {
		const keys = Object.keys(obj).sort();
		var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
		for (var i = 0; i < keys.length; i++) { //遍历keys数组
			newObj[keys[i]] = obj[keys[i]];
		}
		return newObj;
	},
	to_back: function() {
		uni.navigateBack({});
	},
	//跳转到本地信息列表页
	to_post_list: function(item) {
		uni.setStorageSync("temp", item);
		this.to_nav_page('/pages/index/post/post_list');
	},
	//本地信息转到编辑页面
	to_post_edit: function(item) {
		uni.setStorageSync("temp", item);
		if (item.middle) {
			uni.navigateTo({
				url: "post_edit_middle"
			})
		} else {
			uni.navigateTo({
				url: "post_edit"
			})
		}
	},
	//API 请求携带的 header
	header: function() {
		return {
			source: 'uniapp',
			user_token: uni.getStorageSync('user_token'),
			shop_token: uni.getStorageSync('shop_token')
		}
	},
	to_bean_detail: function(item, url) {
		uni.setStorageSync("bean", item)
		this.to_nav_page(url)
	},
	//self:vue对象,url API接口连接,append是否追加
	search_bean: function(self, url, append) {
		if (!append) {
			self.bean.from = 0;
		}else{
			self.bean.from = self.bean.from + self.bean.rows;
		}

		uni.request({
			url: self.host + url,
			method: "POST",
			header: this.header(),
			data: self.bean,
			success: (res) => {
				if (res.data.flag == 0) {
					self.bean = res.data.bean;

					res.data.beanList.forEach((item) => {
						//格式化日期
						item.createTime = this.format(item.createTime, true)
						item.createTime2 = this.format(item.createTime, false)
					});
					if (append) { //是否追加 比如 上拉加载
						self.beanList = self.beanList.concat(res.data.beanList);
					} else {
						self.beanList = res.data.beanList;
					}
				} else {
					this.toast(res.data.msg)
				}
				uni.hideToast();
				
				//是否已加载列表 如果空 则实现空白提示
				self.loaded = true;
			}
		})
	},
	//stay 删除操作,是否停留在当前页 比如在列表页中删除, 将这个设置为true即可
	to_del_bean: function(self, url, stay) {
		uni.showModal({
			title: '您确定要删除吗？',
			content: '删除后不可恢复,请谨慎操作！',
			success: (res) => {
				if (res.confirm) {
					uni.request({
						url: self.host + url,
						method: "GET",
						header: this.header(),
						success: (res) => {
							if (res.data.flag == 0) {
								uni.showToast({
									title: res.data.msg,
									icon: 'success',
									success: (res) => {
										if (stay) {
											//停留在列表页中,直接删除 beanIndex
											self.beanList.splice(self.beanIndex, 1);
										} else {
											let pages = getCurrentPages(); //获取所有页面栈实例列表
											if (pages.length >= 2) {
												let prevPage = pages[pages.length - 2]; //上一页实例
												//删除上一列表页元素
												prevPage.$vm.beanList.splice(prevPage.$vm.beanIndex, 1);
											}
											this.to_back();
										}
									}
								})
							}
						}
					})
				}
			}
		});
	},
	//下拉加载共用
	to_reach_bottom: function(self) {
		if (self.bean.from >= self.bean.counts) {
			this.toast("没有更多数据了")
		} else {
			uni.showToast({
				title: "正在加载中",
				success: (res) => {
					self.search_bean(true)
				}
			})
		}
	},
	//tab 标题栏展示self:vue实例, e为选择事件,k为需要改变的键值
	to_tab_select: function(self, e, k) {
		self.tab_cur = e.currentTarget.dataset.id;
		self.tab_left = (e.currentTarget.dataset.id - 1) * 60;

		if (self.tab_cur == 0) {
			self.bean[k] = null;
		} else {
			for (var i = 1; i < self.tabs.length; i++) {
				if (self.tabs[i].state == self.tab_cur) {
					self.bean[k] = self.tabs[i].text;
					break;
				}
			}
		}
		self.search_bean()
	},
	// 预览图片
	to_view_image: function(index, urls) {
		uni.previewImage({
			current: index,
			urls: urls,
			indicator: 'number',
			loop: true,
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
			}
		});
	},
	to_nav_page: function(page) {
		uni.navigateTo({
			url: page
		});
	},
	to_red_page: function(page) {
		uni.redirectTo({
			url: page
		});
	},
	toast: function(msg) {
		uni.showToast({
			title: msg,
			icon: 'none'
		});
		setTimeout(()=>{
			uni.hideToast();
		},1500);
	},
	get_source: function() { //获取所属终端
		let source = "h5_browser";

		//#ifdef APP-PLUS
		let res = uni.getSystemInfoSync();
		source = 'app_' + res.platform; //app_ios || app_android
		//#endif

		//#ifdef H5
		let browser = navigator.userAgent.toLocaleLowerCase()
		if (browser.indexOf('micromessenger') > -1) {
			source = 'h5_weixin'
		} else {
			source = 'h5_browser'
		}
		//#endif

		//#ifdef MP-WEIXIN
		source = 'mp_weixin'
		//#endif

		//#ifdef MP-ALIPAY
		source = 'mp_alipay'
		//#endif

		//#ifdef MP-BAIDU
		source = 'mp_baidu'
		//#endif

		//#ifdef MP-TOUTIAO
		source = 'mp_toutiao'
		//#endif

		//#ifdef MP-QQ
		source = 'mp_qq'
		//#endif

		return source;
	},
	alert: function(title, content) { //只显示确定按钮
		if (content == "" || content == null || content === undefined) {
			content = "尚云商-友情提示:官方网站:https://byteyun.net 请用已绑定的手机号/邮箱进行登录!"
		}
		uni.showModal({
			title: title,
			content: content,
			showCancel: false
		})
	},
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	_format: function(number) {
		return (number < 10 ? ('0' + number) : number);
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	nowDate: function() { //返回当前日期 搜索日期的最大值 或 最小值
		var date = new Date()
		return date.getFullYear() + '-' + this._format(date.getMonth() + 1) + '-' + this._format(date.getDate())
	},
	format: function(ts, flag) { //将时间戳 格式化日期 或者 日期时间
		if (typeof ts !== 'number') {
			return ts
		}
		var date = new Date(ts)

		if (flag) { //true 格式化日期 不带时间
			return date.getFullYear() + '-' + this._format(date.getMonth() + 1) + '-' + this._format(date.getDate());
		} else {
			return date.getFullYear() + '-' + this._format(date.getMonth() + 1) + '-' + this._format(date.getDate()) + ' ' +
				this._format(date.getHours()) + ':' + this._format(date.getMinutes()) + ':' + this._format(date.getSeconds());
		}
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},
	tsFormat: function(timestamp) { //将时间戳 格式化为 刚刚 几分几秒 yyyy-mm-dd
		if (typeof timestamp !== 'number') {
			return timestamp
		}

		function zeroize(num) {
			return (String(num).length == 1 ? '0' : '') + num;
		}

		var curTimestamp = new Date().getTime(); //当前时间戳
		var timestampDiff = parseInt((curTimestamp - timestamp) / 1000); // 参数时间戳与当前时间戳相差毫秒数

		var curDate = new Date(curTimestamp); // 当前时间日期对象
		var tmDate = new Date(timestamp); // 参数时间戳转换成的日期对象

		var Y = tmDate.getFullYear(),
			m = tmDate.getMonth() + 1,
			d = tmDate.getDate();
		var H = tmDate.getHours(),
			i = tmDate.getMinutes(),
			s = tmDate.getSeconds();

		if (timestampDiff < 60) { // 一分钟以内
			return "刚刚";
		} else if (timestampDiff < 3600) { // 一小时前之内
			return Math.floor(timestampDiff / 60) + "分钟前";
		} else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
			return '今天' + zeroize(H) + ':' + zeroize(i);
		} else {
			var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
			if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
				return '昨天' + zeroize(H) + ':' + zeroize(i);
			} else if (curDate.getFullYear() == Y) {
				return zeroize(m) + '-' + zeroize(d);
			} else {
				return Y + '-' + zeroize(m) + '-' + zeroize(d);
			}
		}
	},
	formatTime: function(time) { //格式化 时间
		if (typeof time !== 'number' || time < 0) {
			return time
		}
		var hour = parseInt(time / 3600)
		time = time % 3600
		var minute = parseInt(time / 60)
		time = time % 60
		var second = time

		return ([hour, minute, second]).map(function(n) {
			n = n.toString()
			return n[1] ? n : '0' + n
		}).join(':')
	},
	check_reg: function(value, reg, msg) { //正则检测 提示信息
		if (value == "" || value == null || value === undefined) {
			this.toast(msg);
			return false;
		}
		//将字符串转换为正则使用. 对于RegExp而言不需要携带两端的/ 对于 eval 需要
		if (reg.startsWith('/')) {
			reg = reg.substr(1); //删除第一个字符
		}
		if (reg.endsWith('/')) { //删除最后一个字符
			reg = reg.substring(0, reg.length - 1)
		}
		if (!new RegExp(reg).test(value)) {
			this.toast(msg);
			return false;
		}
		return true;
	}
};

module.exports = {
	util: util
}
